# -*- coding: utf-8 -*-
# vim:et:sw=4:sts=4:ai:nosi

import re
from jinja2 import evalcontextfilter, Markup, escape

_paragraph_re = re.compile(r'\n{2,}')

@evalcontextfilter
def nl2br(eval_ctx, value):
    value = value.replace('\r\n', '\n')
    result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br/>\n'))
                          for p in _paragraph_re.split(escape(value)))
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

